import CryptoJS from 'crypto-js';

/**
 * 阿里云OSS配置
 */
const OSS_CONFIG = {
    accessKeyId: 'LTAI5tG6chRmzwe3uKLrXdmA',
    accessKeySecret: '8v3FNE84HMmCNS8kYX3pXjBzgp5fes',
    bucket: 'robot-toy',
    region: 'oss-cn-hangzhou', // 根据实际情况修改region
    endpoint: 'oss-cn-hangzhou.aliyuncs.com' // 根据实际情况修改
};

/**
 * 生成OSS签名
 */
function generateSignature(policy, accessKeySecret) {
    const bytes = CryptoJS.HmacSHA1(policy, accessKeySecret);
    return CryptoJS.enc.Base64.stringify(bytes);
}

/**
 * 生成Policy
 */
function generatePolicy(dir) {
    const date = new Date();
    date.setHours(date.getHours() + 1); // 1小时后过期
    const expiration = date.toISOString();

    const policyObj = {
        expiration: expiration,
        conditions: [
            ['content-length-range', 0, 1048576000], // 最大1GB
            ['starts-with', '$key', dir]
        ]
    };

    const policyBase64 = CryptoJS.enc.Base64.stringify(
        CryptoJS.enc.Utf8.parse(JSON.stringify(policyObj))
    );

    return policyBase64;
}

/**
 * 获取文件目录名（日期+用户名）
 */
function getFileDir() {
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');

    // 获取用户昵称
    const nickName = uni.getStorageSync('nickName') || 'user';
    const safeNickName = nickName.replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '_');

    return `voice/${year}${month}${day}_${safeNickName}/`;
}

/**
 * 生成唯一文件名
 */
function generateFileName(fileExt = 'mp3') {
    const timestamp = Date.now();
    const random = Math.random().toString(36).substring(2, 15);
    return `${timestamp}_${random}.${fileExt}`;
}

/**
 * 上传文件到阿里云OSS
 * @param {String} filePath - 本地文件路径
 * @param {String} fileExt - 文件扩展名，默认mp3
 * @returns {Promise} - 返回OSS文件URL
 */
export function uploadToOSS(filePath, fileExt = 'mp3') {
    return new Promise((resolve, reject) => {
        console.log('========== OSS上传开始 ==========');
        console.log('📁 本地文件路径:', filePath);

        // 生成文件目录和文件名
        const dir = getFileDir();
        const fileName = generateFileName(fileExt);
        const key = dir + fileName;

        console.log('📂 OSS目录:', dir);
        console.log('📄 文件名:', fileName);
        console.log('🔑 完整Key:', key);

        // 生成Policy和Signature
        const policyBase64 = generatePolicy(dir);
        const signature = generateSignature(policyBase64, OSS_CONFIG.accessKeySecret);

        // OSS上传URL
        const uploadUrl = `https://${OSS_CONFIG.bucket}.${OSS_CONFIG.endpoint}`;

        console.log('🌐 上传URL:', uploadUrl);

        // 上传到OSS
        uni.uploadFile({
            url: uploadUrl,
            filePath: filePath,
            name: 'file',
            formData: {
                key: key,
                policy: policyBase64,
                OSSAccessKeyId: OSS_CONFIG.accessKeyId,
                signature: signature,
                success_action_status: '200'
            },
            success: (res) => {
                console.log('========== OSS上传成功 ==========');
                console.log('✅ 状态码:', res.statusCode);
                console.log('📦 响应:', res.data);

                if (res.statusCode === 200) {
                    // 生成访问URL
                    const ossUrl = `https://${OSS_CONFIG.bucket}.${OSS_CONFIG.endpoint}/${key}`;
                    console.log('🎉 文件URL:', ossUrl);
                    console.log('================================');
                    resolve(ossUrl);
                } else {
                    console.error('❌ 上传失败，状态码:', res.statusCode);
                    reject(new Error(`上传失败: ${res.statusCode}`));
                }
            },
            fail: (err) => {
                console.error('========== OSS上传失败 ==========');
                console.error('❌ 错误信息:', err.errMsg);
                console.error('📋 错误详情:', JSON.stringify(err));
                console.error('================================');
                reject(new Error(`OSS上传失败: ${err.errMsg}`));
            }
        });
    });
}

/**
 * 获取OSS文件的公网访问URL
 * @param {String} key - OSS文件key
 * @returns {String} - 公网访问URL
 */
export function getOSSUrl(key) {
    return `https://${OSS_CONFIG.bucket}.${OSS_CONFIG.endpoint}/${key}`;
}
